/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.proxy.invocation;

import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.proxy.MethodInterceptor;
import com.aduib.boot.common.proxy.MethodInvocation;
import com.aduib.boot.common.util.ArrayUtils;
import com.aduib.boot.common.util.ClassUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @description: ReflectionMethodInvocation
 * @author: zzh
 * @date: 2021/10/26 16:02
 */
public class ReflectionMethodInvocation implements MethodInvocation {

  protected final Object proxy;

  protected final Object target;

  protected final Method method;
  private final Class<?> targetClass;
  private final List<String> objectMethods;
  private final List<MethodInterceptor> methodInterceptorList;
  protected Object[] arguments;

  public ReflectionMethodInvocation(
      Object proxy,
      Object target,
      Method method,
      Object[] arguments,
      Class<?> targetClass,
      List<MethodInterceptor> methodInterceptorList) {
    this.proxy = proxy;
    this.target = target;
    this.method = method;
    this.arguments = arguments;
    this.targetClass = targetClass;
    this.objectMethods = initObjectMethod();
    this.methodInterceptorList = methodInterceptorList;
  }

  protected Object invokeMethod() throws Throwable {
    if (target != null) {
      return ClassUtils.invokeMethod(this.target, this.method, this.arguments);
    }
    return null;
  }

  @Override
  public Object getProxy() {
    return proxy;
  }

  @Override
  public Method getMethod() {
    return method;
  }

  @Override
  public Object[] getArguments() {
    return arguments;
  }

  @Override
  public Object getThis() {
    return target;
  }

  @Override
  public Object proceed() throws Throwable {
    Object sourceObject = target;
    method.setAccessible(true);
    if (objectMethods.contains(method.getName())) {
      if (sourceObject != null) {
        return method.invoke(sourceObject, arguments);
      } else {
        return null;
      }
    }

    Object result = null;
    if (Objects.isNull(methodInterceptorList) || methodInterceptorList.isEmpty()) {
      try {
        ClassUtils.setAccessible(method);
        result = invokeMethod();
      } catch (InvocationTargetException e) {
        throw new CommonException("invoke method [{}], args: [{}] ,object: [{}] fail", method, ArrayUtils.toString(arguments),sourceObject);
      }
    }

    // 开始前回调
    if (invokeBeforeAspect(method, arguments)) {
      try {
        ClassUtils.setAccessible(method);
        result = invokeMethod();
      } catch (InvocationTargetException e) {
        // 异常回调（只捕获业务代码导致的异常，而非反射导致的异常）
        invokeAfterExceptionAspect(method, arguments, e);
      }
    }

    // 结束执行回调
    if (invokeAfterAspect(method, arguments, result)) {
      return result;
    }
    return result;
  }

  /**
   * 方法执行前
   *
   * @param method
   * @param args
   * @param result
   * @return
   */
  private boolean invokeAfterAspect(Method method, Object[] args, Object result) {
    boolean finishFlag = false;
    for (MethodInterceptor methodInterceptor : methodInterceptorList) {
      if (methodInterceptor.after(target, method, args, result)) {
        finishFlag = true;
      }
    }
    return finishFlag;
  }

  /**
   * 方法执行出现异常
   *
   * @param method
   * @param args
   * @param e
   * @throws InvocationTargetException
   */
  private void invokeAfterExceptionAspect(Method method, Object[] args, InvocationTargetException e)
      throws InvocationTargetException {
    for (MethodInterceptor methodInterceptor : methodInterceptorList) {
      if (methodInterceptor.afterException(target, method, args, e.getTargetException())) {
        throw e;
      }
    }
  }

  /**
   * 方法执行结束后
   *
   * @param method
   * @param args
   * @return
   */
  private boolean invokeBeforeAspect(Method method, Object[] args) {
    boolean result = false;
    for (MethodInterceptor methodInterceptor : methodInterceptorList) {
      if (methodInterceptor.before(target, method, args)) {
        result = true;
      }
    }
    return result;
  }

  private List<String> initObjectMethod() {
    ArrayList<String> objectMethods = new ArrayList<>();
    Method[] declaredMethods = Object.class.getDeclaredMethods();
    for (Method declaredMethod : declaredMethods) {
      objectMethods.add(declaredMethod.getName());
    }

    return objectMethods;
  }
}
